package com.web.base.core.provider;

import com.blue.jdbc.Page;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.core.cache.BankCache;
import com.web.base.core.exception.BankException;
import com.web.base.core.facade.BankFacade;
import com.web.base.core.message.BankRequest;
import com.web.base.core.message.BankResponse;
import com.web.base.core.model.Bank;
import com.web.base.core.service.BankService;
import com.web.base.core.util.BankConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

/**
 * 银行接口实现类
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2018年06月19日
 */
@Component("coreBankProvider")
public class BankProvider implements BankFacade
{
	@Autowired
	private BankService bankService;
	@Autowired
	private BankCache bankCache;
	
	public BankProvider()
	{
	}

	@Override
	public BankResponse add(BankRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Bank bank = BankConvertor.toBank(request);
		bank = bankService.save(bank);
		bankCache.delete();
		BankResponse response = BankConvertor.toResponse(bank);
		return response;
	}

	@Override
	public BankResponse update(BankRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Bank bank = BankConvertor.toBank(request);
		bank = bankService.save(bank);
		bankCache.delete();
		BankResponse response = BankConvertor.toResponse(bank);
		return response;
	}

	@Override
	public BankResponse get(Integer id)
	{
		if (id == null)
			throw new BankException("ID不能为空");
			
		Bank bank = bankCache.get(id);
		BankResponse response = BankConvertor.toResponse(bank);
		return response;
	}

	@Override
	public Map<Integer, BankResponse> getList(Collection<Integer> idList)
	{
		Map<Integer, Bank> map = bankCache.getList(idList);
		Map<Integer, BankResponse> responseMap = BankConvertor.toResponse(map);
		return responseMap;
	}

	@Override
	public BankResponse getByCode(String code)
	{
		if (code == null || code.isEmpty())
			throw new BankException("代码不能为空");

		Bank bank = bankCache.getByCode(code);
		BankResponse response = BankConvertor.toResponse(bank);
		return response;
	}

	@Override
	public Page<BankResponse> listPage(BankRequest request, int start, int size)
	{
		Bank bank = BankConvertor.toBank(request);
		Page<Bank> page = new Page<>(size);
		page.setCurPage(start);
		page = bankService.list(bank, page);
		Page<BankResponse> pageResponse = BankConvertor.toResponse(page);
		return pageResponse;
	}

	@Override
	public void refresh()
	{
		bankCache.delete();
	}

}
